import { defineStore } from 'pinia';
import { store } from '../index';
import { useTagsViewStore } from './tagsView';
import { usePermissionStore } from './permission';

type IUserInfo = {
  username: string;
} & Record<string, any>;

interface UserState {
  userInfo?: IUserInfo;
  token: string;
  refreshToken: string;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      userInfo: undefined,
      token: '',
      refreshToken: ''
    };
  },
  persist: {
    key: '__userinfo__'
  },
  getters: {
    getToken(): string {
      return this.token;
    },
    getRefreshToken(): string {
      return this.refreshToken;
    },
    getUserInfo(): IUserInfo | undefined {
      return this.userInfo;
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setRefreshToken(refreshToken: string) {
      this.refreshToken = refreshToken;
    },
    setUserInfo(userInfo?: IUserInfo) {
      this.userInfo = userInfo;
    },
    clear() {
      const tagsViewStore = useTagsViewStore();
      tagsViewStore.delAllViews();
      const permissionStore = usePermissionStore();
      permissionStore.reset();
      this.setToken('');
      this.setRefreshToken('');
      this.setUserInfo(undefined);
    },
    login(params: Recordable) {
      return new Promise((resolve) => {
        console.error(params);
        this.setToken('123456');
        this.setUserInfo({ username: '管理员' });
        resolve('');
      });
    },
    logout() {
      this.clear();
    }
  }
});

export const useUserStoreWithOut = () => {
  return useUserStore(store);
};
